package com.effectivsocial.extention.repository;

import javax.servlet.ServletRequest;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 *
 * 
 * @author Dhrubo
 */
@Slf4j
public class PageableArgumentResolver implements HandlerMethodArgumentResolver {
	
	private final Pageable DEFAULT = new PageRequest(0, 10);
	
	public Object resolveArgument(MethodParameter methodParameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		
		Pageable pageable = null;
		
		if (methodParameter.getParameterType().equals(Pageable.class)) {
			ServletRequest servletRequest = (ServletRequest) webRequest.getNativeRequest();
			String page = servletRequest.getParameter("page");
			String pageSize = servletRequest.getParameter("pagesize");
			
			if(StringUtil.isAllBlank(page, pageSize)) {
				pageable = DEFAULT;
			}
			else{
				pageable = new PageRequest(Integer.parseInt(page), Integer.parseInt(pageSize));
			}
				
		}
		
		mavContainer.addAttribute("pagerequest", pageable);
		return pageable;
	}

	public boolean supportsParameter(MethodParameter methodParameter) {
		log.info("########### Method param = {}" , methodParameter.getParameterType());
		return methodParameter.getParameterType().equals(Pageable.class);
	}

	
	
}
